package com.edu.controller.front.pay;

import com.edu.service.ordertab.OrderService;
import com.edu.service.ordertab.OrderServiceImpl;
import com.edu.utils.ParamFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author ZCN
 * @version 1.0
 * @date 2021/11/25 10:50
 */
@WebServlet("/front/pay/notify")
public class NotifyServlet extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            ParamFormat.format(req, resp);

            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = req.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }


            // 完成自己业务
            // 拿到订单号
            // 商户订单号
            String out_trade_no = params.get("out_trade_no");
            orderService.updateAfterPay(out_trade_no);

            //成功处理后返回success
            resp.getWriter().write("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
